<?php

namespace App\Http\Controllers\admin;

use App\Models\Device;
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\common\PublicController;
//模型
use App\Models\Building;
use App\Models\Room;
use App\Models\Electric;

class ElectricController extends PublicController
{
    private $type_id = '9';
    //设备列表页面
    public function getIndex(Request $request)
    {
        /*搜索条件始*/
        //搜索条件
        $get['area'] = $request -> input('area','');
        if($get['area']){
            $this -> where .= ' -> where("area.name","like","%".$get["area"]."%")';
        }
        $get['room'] = $request -> input('room','');
        if($get['room']){
            $this -> where .= ' -> where("room.name","like","%".$get["room"]."%")';
        }
        $get['dev'] = $request -> input('dev','');
        if($get['dev']){
            $this -> where .= ' -> where("DevEUI","like","%".$get["dev"]."%")';
        }
        $get['model'] = $request -> input('model','');
        if($get['model']){
            $this -> where .= ' -> where("model.name","like","%".$get["model"]."%")';
        }
        /*搜索条件末*/
        /*代理商搜索始*/
        //获取自身及旗下所有代理商
        $agentInfo = $this -> agentInfo($request -> cookie('logon')['agent_id']);
        /*代理商搜索末*/
        $get['agent_id'] = $this -> agent_id;
        //给页面分配数据
        $deviceInfo = $this -> deviceInfo($this -> type_id,$get);
        return view('admin.electric.index',['data'=>$deviceInfo['data'],'info'=>$deviceInfo['info'],'agentInfo'=>$agentInfo,'request'=>$request -> all(),'get'=>$get,'areaids' => $this->area_ids]);
    }

    //添加设备页面
    public function getCreate()
    {
        //获取所有的设备
        $deviceInfo = DB::table('device') -> select('DevEUI') -> get();
        //获取代理商下的所有区域
        if($this -> area_ids === '0'){
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> get();
        }else{
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> whereIn("area.id",explode(",",$this -> area_ids)) -> get();
        }
        //获取烟感设备的所有型号
        $modelInfo = DB::table('model') -> where('type_id',$this -> type_id) -> get();
        return view('admin.electric.create',['deviceInfo' => $deviceInfo,'areaInfo'=>$areaInfo,'modelInfo'=>$modelInfo]);
    }

    //添加处理页面
    public function postStore(Request $request)
    {
        $info = $request -> except('_token');
        $info['agent_id'] = $this -> agent_id;
        //添加到lora
        $this->addDevice($this->type_id,$info['DevEUI']);
        //判断设备是否已被绑定
        $res = Device::where('DevEUI',$info['DevEUI']) -> first() -> status;
        if(!$res){
            //添加到烟感设备表
            $resObj = Electric::create($info);
            if($resObj){
                $resObj -> num = 'ET'.str_pad($resObj->id,6,0,STR_PAD_LEFT);
                if($resObj -> save()){
                    //修改设备绑定状态
                    Device::where('DevEUI',$info['DevEUI']) -> update(['status'=>1]);
                    $data['status'] = 1;
                }else{
                    $data['status'] = -1;
                }
            }else{
                $data['status'] = -1;
            }
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //编辑设备页面
    public function getEdit(Request $request)
    {
        $id = $request -> input('id');
        //获取烟感设备信息
        $Info = Electric::find($id);
        //获取区域建筑id
        if($Info -> room_id&&Room::find($Info -> room_id)){
            //获取建筑id
            $Info['area_id'] = Room::find($Info -> room_id) -> area_id;
        }else{
            $Info['area_id'] = null;
        }
        //获取代理商下的所有区域
        if($this -> area_ids === '0'){
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> get();
        }else{
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> whereIn("area.id",explode(",",$this -> area_ids)) -> get();
        }
        //获取该房间所在区域的所有建筑
        $roomInfo = Room::where('area_id',$Info['area_id']) -> get() -> toarray();
        //获取烟感设备的所有型号
        $modelInfo = DB::table('model') -> where('type_id',$this -> type_id) -> get();
        return view('admin.electric.edit',['data'=>$Info,'areaInfo'=>$areaInfo,'roomInfo'=>$roomInfo,'modelInfo'=>$modelInfo]);
    }

    //编辑处理页面
    public function postUpdate(Request $request)
    {
        $id = $request -> input('id');
        $info = $request -> except('_token','id');
        //修改smoke表
        $res = Electric::find($id) -> update($info);
        if($res){
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //删除处理页面
    public function postDestroy(Request $request)
    {
        $id = $request -> input('id');
        //查询设备表
        $DevEUI = Electric::find($id) -> DevEUI;
        $this -> delDevice($DevEUI);
        //查询区域和客户的关系表并删除
        $res = Electric::destroy($id);
        if($res){
            //修改设备绑定状态
            Device::where('DevEUI',$DevEUI) -> update(['status'=>0]);
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //通知状态处理页面
    public function postStatus(Request $request){
        $id = $request -> input('id');
        $status = $request -> input('status');
        //修改设备表
        $res = Electric::find($id) -> update(['status'=>$status]);
        if($res){
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //文件下载
    public function getUpload(){
        $data = DB::table("electric")
            -> leftJoin("room","electric.room_id","=","room.id")
            -> leftJoin("area","room.area_id","=","area.id")
            -> leftJoin("model","electric.model_id","=","model.id")
            -> where("electric.agent_id",$this -> agent_id)
            -> select('num','DevEUI','area.name as area_name','room.name as room_name','model.name as model_name','loc')
            -> get();
        echo '<!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                <meta charset="utf-8">
                <title>下载页面</title>
                <meta name="renderer" content="webkit">
                <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
                <meta name="apple-mobile-web-app-status-bar-style" content="black">
                <meta name="apple-mobile-web-app-capable" content="yes">
                <meta name="format-detection" content="telephone=no">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <style type="text/css">
                table {
                   margin:0;
                   padding:0;
                   border-collapse: collapse;
                   border-spacing: 0;
                   margin: 0 auto;
                }
                table tr {
               /* border: 1px solid #ddd;*/
                padding: 5px;
                }
                table th, table td {
                padding:5px;
                text-align: center;
                border:1px solid #f1f1f1;
                color:black;
                }
                table td{
                 color:black;
                 font-size: 15px;
                }
                table th {
                text-transform: uppercase;
                font-size: 1em;
                letter-spacing: 1px;
              }
                </style>
                </head>
                <body>
                    <table id="table1">
                        <thead>             
                                <th style="font-weight: bold;">编号</th>
                                <th style="font-weight: bold;">DevEUI</th>
                                <th style="font-weight: bold;">型号</th>
                                <th style="font-weight: bold;">区域</th>
                                <th style="font-weight: bold;">房间</th>
                                <th style="font-weight: bold;">具体位置</th>
                        </thead>
                        <tbody id="tbody1">';
        foreach ($data as $v){
            echo "<tr >
                                    <td>".$v['num']."</td>
                                    <td>".$v['DevEUI']."</td>
                                    <td>".$v['area_name']."</td>                 
                                    <td>".$v['room_name']."</td>                  
                                    <td>".$v['model_name']."</td>                  
                                    <td>".$v['loc']."</td>                  
                                 </tr>";
        }
        echo '</tbody>
                    </table>
                    </body>
                    </html>';
        ob_start(); //打开缓冲区
        header("Cache-Control: public");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) {
            header('Content-Disposition: attachment; filename=electric.doc');
        }else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) {
            Header('Content-Disposition: attachment; filename=electric.doc');
        } else {
            header('Content-Disposition: attachment; filename=electric.doc');
        }
        header("Pragma:no-cache");
        header("Expires:0");
        ob_end_flush();//输出全部内容到浏览器
    }
}
